package com.gddb.xwj.common.mybatis;

import com.gddb.xwj.common.entity.TestEntity;
import com.gddb.xwj.utils.DateUtil;
import com.gddb.xwj.utils.ReflectionUtil;
import org.apache.ibatis.jdbc.SQL;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author xuwj
 * @Description: ${todo}
 * @CreateTime 2020/1/9 23:16
 * @Version 1.0
 */
public class BaseProvider {

    /**
     * 自定义封装sql语句_插入操作
     *
     * @param map
     * @return
     */
     public String save(Map<String, Object> map) {
        //根据入参获取实体类
        Object obj = map.get("obj");
        //根据入参获取表名
        String table = (String) map.get("table");
        //生成添加sql语句。
        //步骤：使用反射机制加载这个类的所有属性
        SQL sql = new SQL() {
            {
                INSERT_INTO(table);
                VALUES(ReflectionUtil.getAllField(obj), ReflectionUtil.getAllFieldValue(obj));
            }
        };
        return sql.toString();
    }

    /**
     * 自定义封装sql语句_更新操作
     * @param map
     * @return
     */
    public String update(Map<String,Object> map){
        Object obj = map.get("obj");
        String table = (String) map.get("table");
        Long id = (Long) map.get("id");
        SQL sql =new SQL(){
            //抽象方法 必须实现  此处采用匿名内部类
            {
                UPDATE(table);
                SET(ReflectionUtil.setAllFieldValue(obj));
                WHERE(" id = " + id);
            }
        };
        return sql.toString();
    }

    /**
     * 测试用
     * @param args
     */
    public static void main(String[] args) {
        HashMap<String, Object> map = new HashMap<>();
        TestEntity testEntity = new TestEntity();
        testEntity.setEmail("qqq@163.com");
        testEntity.setCreateTime(DateUtil.getTimestamp());
        map.put("obj",testEntity);
        map.put("table","shop_user");
        map.put("id",1l);
        //测试更新语句
        //String sql = update(map);
        //System.out.println(sql);
        /*
        UPDATE shop_user
        SET email = 'qqq@163.com',createTime = '2020-01-10 01:28:32.859'
        WHERE ( id = 1)
        * */

        //测试新增
        TestEntity testEntity1 = new TestEntity();
        testEntity1.setUserName("许文杰");
        testEntity1.setPassword("123");
        testEntity1.setEmail("test1@163.com");
        testEntity1.setPhone("13008889301");
        testEntity1.setCreateTime(DateUtil.getTimestamp());
        testEntity1.setUpdateTime(DateUtil.getTimestamp());
        map.put("obj",testEntity1);
        map.put("table","shop_user");
        //String sql = save(map);
        //System.out.println(sql);
        /*
        *INSERT INTO shop_user
         (userName,password,phone,email,id,createTime,updateTime)
        VALUES ('许文杰','123','13008889301','test1@163.com',null,'2020-01-10 01:45:17.192','2020-01-10 01:45:17.192')
        * */

    }
}
